package net.dnw.practicesummary.mvp.net;



import net.dnw.practicesummary.mvp.BaseApplication;
import net.dnw.practicesummary.mvp.utils.ApiConstants;
import net.dnw.practicesummary.mvp.utils.Logger;
import net.dnw.practicesummary.mvp.utils.NetUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 配置Retrofit（配置网络缓存cache、配置持久cookie免登录）
 */

public class BaseRetrofit {

    private static final String TAG = BaseRetrofit.class.getSimpleName();
    private final OkHttpClient mClient;

    public OkHttpClient getClient() {
        return mClient;
    }

    public BaseRetrofit() {
        mClient = new OkHttpClient.Builder()
                .addInterceptor(new MoreBaseUrlInterceptor())
                .addInterceptor(new LoggingInterceptor())
                .build();

    }


    public class MoreBaseUrlInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //获取原始的originalRequest
            Request originalRequest = chain.request();
            //获取老的url
            HttpUrl oldUrl = originalRequest.url();
            //获取originalRequest的创建者builder
            Request.Builder builder = originalRequest.newBuilder();
            //获取头信息的集合如：manage,mdffx
            List<String> urlnameList = originalRequest.headers("urlname");
            if (urlnameList != null && urlnameList.size() > 0) {
                //删除原有配置中的值,就是namesAndValues集合里的值
                builder.removeHeader("urlname");
                //获取头信息中配置的value,如：URL或者URL2
                String urlname = urlnameList.get(0);
                HttpUrl baseURL = null;
                //根据头信息中配置的value,来匹配新的base_url地址
                if ("URL".equals(urlname)) {
                    baseURL = HttpUrl.parse(ApiConstants.BASE_URL);
                } else if ("URL2".equals(urlname)) {
                    baseURL = HttpUrl.parse(ApiConstants.BASE_URL2);
                } else {
                    baseURL = HttpUrl.parse(ApiConstants.BASE_URL);
                }
                //重建新的HttpUrl，需要重新设置的url部分
                HttpUrl newHttpUrl = oldUrl.newBuilder()
                        .scheme(baseURL.scheme())//http协议如：http或者https
                        .host(baseURL.host())//主机地址
                        .port(baseURL.port())//端口
                        .build();
                //获取处理后的新newRequest
                Request newRequest = builder.url(newHttpUrl).build();
                return chain.proceed(newRequest);
            } else {
                return chain.proceed(originalRequest);
            }

        }

    }

    class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //这个chain里面包含了request和response，所以你要什么都可以从这里拿
            Request request = chain.request();
            long t1 = System.nanoTime();//请求发起的时间
            Logger.e(TAG, String.format("发送请求 %s on %s%n%s", request.url(), chain.connection(), request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();//收到响应的时间
            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
            //个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);
            Logger.e(TAG, String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s", response.request().url(), responseBody.string(), (t2 - t1) / 1e6d, response.headers()));
            return response;
        }
    }

}
